package com.ts.api.http.platform.biz;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gitee.apanlh.util.algorithm.encrypt.symmetric.AES;
import com.gitee.apanlh.util.base.ChooseEq;
import com.gitee.apanlh.util.base.CollUtils;
import com.gitee.apanlh.util.base.Eq;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.util.valid.ValidParam;
import com.gitee.apanlh.web.model.vo.RequestVO;
import com.ts.api.http.platform.entity.apply.ApiPlatFormApplyAnXinFenQi;
import com.ts.api.http.platform.entity.apply.ApiPlatFormApplyAnXinFenQiData;
import com.ts.api.http.platform.entity.dataexchange.ApiPlatDataExchangeAnXinFenQi;
import com.ts.api.http.platform.entity.dataexchange.ApiPlatDataExchangeAnXinFenQiData;
import com.ts.api.module.api.convert.core.annotation.ApiPlan;
import com.ts.api.module.api.convert.core.annotation.ApiPlanConvertType;
import com.ts.api.module.api.convert.core.entity.ApiApplyParameter;
import com.ts.api.module.api.convert.core.entity.ApiBizStatus;
import com.ts.api.module.api.convert.core.entity.ApiDataExchangeParameter;
import com.ts.api.module.api.convert.platform.entity.RespPlatformNoticeApply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMd5Apply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMd5DataExchange;
import com.ts.api.module.api.convert.platform.handler.ApiPlatformPhoneMd5ConvertHandler;
import com.ts.api.module.api.entity.ApiProtocol;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 安心分期-e时代2
 *
 * 文档：https://ov5pdwnlipy.feishu.cn/docx/DZkLdGYC1ozzhPxGeuWc66g5nTf
 *
 * @author ZJQ
 */
@ApiPlan(productId = "691", type = ApiPlanConvertType.PLAT_PHONE_MD5)
public class ApiPlatAnXinFenQiPhoneMd5Convert implements ApiPlatformPhoneMd5ConvertHandler {

    private static String KEY = "teP4iTMUGdPhB99I";
    private static String CHANNEL_CODE = "60020391";

    @Override
    public Object dataExchange(ApiDataExchangeParameter apiDataExchangeParameter) {

        ApiPlatDataExchangeAnXinFenQiData apiPlatDataExchangeAnXinFenQiData = new ApiPlatDataExchangeAnXinFenQiData();

        apiPlatDataExchangeAnXinFenQiData.setPhonemd5(apiDataExchangeParameter.getPhoneMd5());
        apiPlatDataExchangeAnXinFenQiData.setName("浩安星");
        apiPlatDataExchangeAnXinFenQiData.setProvince("");
        apiPlatDataExchangeAnXinFenQiData.setCity(apiDataExchangeParameter.getCity().replace("市", ""));
        apiPlatDataExchangeAnXinFenQiData.setAge(Integer.valueOf(apiDataExchangeParameter.getAge()));
        // sex 性别 1男2女
        String sex = apiDataExchangeParameter.getSex();
        Integer sexChoose = ChooseEq.create()
                .when(sex, "0", 1)
                .when(sex, "1", 2)
                .end();
        apiPlatDataExchangeAnXinFenQiData.setSex(sexChoose);
        // loanAmount 预贷款额度
        String loanAmount = apiDataExchangeParameter.getLoanAmount();
        if (ValidParam.isNotEmpty(loanAmount)) {
            Integer money = ChooseEq.create()
                    .when(loanAmount, "1", 30000)
                    .when(loanAmount, "2", 50000)
                    .when(loanAmount, "3", 100000)
                    .when(loanAmount, "4", 200000)
                    .end();
            apiPlatDataExchangeAnXinFenQiData.setLoan(money);
        }

        //  loanTerm 贷款期限
        apiPlatDataExchangeAnXinFenQiData.setLoanTerm(3);

        // loan_use 贷款用途
        String loanUser = apiDataExchangeParameter.getLoanPurpose();
        if (ValidParam.isNotEmpty(loanUser)) {
            Integer value = ChooseEq.create()
                    .when(loanUser, "1", 5)
                    .when(loanUser, "2", 4)
                    .when(loanUser, "3", 8)
                    .when(loanUser, "4", 3)
                    .when(loanUser, "5", 8)
                    .when(loanUser, "6", 6)
                    .end();
            apiPlatDataExchangeAnXinFenQiData.setLoanUse(value);
        }

        // zhima 芝麻分:
        String sesameCredit = apiDataExchangeParameter.getSesameCredit();
        if (ValidParam.isNotEmpty(sesameCredit)) {
            Integer value = ChooseEq.create()
                    .when(sesameCredit, "1", 2)
                    .when(sesameCredit, "2", 3)
                    .when(sesameCredit, "3", 4)
                    .when(sesameCredit, "4", 5)
                    .end();
            apiPlatDataExchangeAnXinFenQiData.setZhima(value);
        }

        //  花呗
        String HuaBei = apiDataExchangeParameter.getHbLimit();
        if (ValidParam.isNotEmpty(HuaBei)) {
            Integer value = ChooseEq.create()
                    .when(HuaBei, "1", 1)
                    .when(HuaBei, "2", 2)
                    .when(HuaBei, "3", 3)
                    .when(HuaBei, "4", 4)
                    .when(HuaBei, "5", 4)
                    .end();
            apiPlatDataExchangeAnXinFenQiData.setHuabei(value);
        }

        //  白条
        String BaiTiao = apiDataExchangeParameter.getBtLimit();
        if (ValidParam.isNotEmpty(BaiTiao)) {
            Integer value = ChooseEq.create()
                    .when(BaiTiao, "1", 1)
                    .when(BaiTiao, "2", 2)
                    .end(3);
            apiPlatDataExchangeAnXinFenQiData.setBaitiao(value);
        }

        //  微粒贷
        apiPlatDataExchangeAnXinFenQiData.setMicroLoan(1);

        // has 社保：
        String socialSecurity = apiDataExchangeParameter.getSocialSecurity();
        if (ValidParam.isNotEmpty(socialSecurity)) {
            Integer value = ChooseEq.create()
                    .when(socialSecurity, "1", 1)
                    .end(2);
            apiPlatDataExchangeAnXinFenQiData.setHas(value);
        }

        // fund 公积金:
        String providentFund = apiDataExchangeParameter.getProvidentFund();
        if (ValidParam.isNotEmpty(providentFund)) {
            Integer value = ChooseEq.create()
                    .when(providentFund, "1", 1)
                    .end(2);
            apiPlatDataExchangeAnXinFenQiData.setFund(value);
        }

        // vehicle  车产：
        String carInfo = apiDataExchangeParameter.getCarInfo();
        if (ValidParam.isNotEmpty(carInfo)) {
            Integer value = ChooseEq.create()
                    .when(carInfo, "1", 1)
                    .end(2);
            apiPlatDataExchangeAnXinFenQiData.setCar(value);
        }

        // house 房产：
        String realEstateInfo = apiDataExchangeParameter.getRealEstateInfo();
        if (ValidParam.isNotEmpty(realEstateInfo)) {
            Integer value = ChooseEq.create()
                    .when(realEstateInfo, "1", 1)
                    .end(2);
            apiPlatDataExchangeAnXinFenQiData.setHouse(value);
        }

        // insurance 保单保险:
        String insurancePolicy = apiDataExchangeParameter.getInsurancePolicy();
        if (ValidParam.isNotEmpty(insurancePolicy)) {
            Integer value = ChooseEq.create()
                    .when(insurancePolicy, "1", 1)
                    .end(2);
            apiPlatDataExchangeAnXinFenQiData.setInsurance(value);
        }

        // overdue 逾期状态:
        String overdue = apiDataExchangeParameter.getOverdue();
        if (ValidParam.isNotEmpty(overdue)) {
            Integer value = ChooseEq.create()
                    .when(overdue, "1", 1)
                    .end(2);
            apiPlatDataExchangeAnXinFenQiData.setOverdue(value);
        }

        // education 学历
        String education = apiDataExchangeParameter.getEducationAttainment();
        if (ValidParam.isNotEmpty(education)) {
            Integer value = ChooseEq.create()
                    .when(education, "1", 1)
                    .when(education, "2", 2)
                    .when(education, "3", 3)
                    .when(education, "4", 4)
                    .when(education, "5", 5)
                    .when(education, "6", 6)
                    .end();
            apiPlatDataExchangeAnXinFenQiData.setEdu(value);
        }

        // creditCard 信用卡
        String creditCard = apiDataExchangeParameter.getCreditLimit();
        if (ValidParam.isNotEmpty(creditCard)) {
            Integer value = ChooseEq.create()
                    .when(creditCard, "1", 1)
                    .end(2);
            apiPlatDataExchangeAnXinFenQiData.setCredit(value);
        }

        // working 职业身份
        String career = apiDataExchangeParameter.getCareer();
        if (ValidParam.isNotEmpty(career)) {
            Integer value = ChooseEq.create()
                    .when(career, "1", 1)
                    .when(career, "2", 3)
                    .when(career, "3", 2)
                    .when(career, "4", 5)
                    .when(career, "5", 4)
                    .end();
            apiPlatDataExchangeAnXinFenQiData.setWorking(value);
        }

        //  是否有企业
        if (ValidParam.isNotEmpty(career)) {
            Integer value = ChooseEq.create()
                    .when(career, "3", 2)
                    .end(1);
            apiPlatDataExchangeAnXinFenQiData.setCompany(value);
        }

        //  客户IP
        apiPlatDataExchangeAnXinFenQiData.setJoinip(apiDataExchangeParameter.getIp());


        AES aes = AES.createEcb(KEY.getBytes());
        Long timestamp = System.currentTimeMillis();
        String jsonStr = JsonUtils.toJson(apiPlatDataExchangeAnXinFenQiData);
        String dataStr = aes.encryptToBase64Str(jsonStr);

        ApiPlatDataExchangeAnXinFenQi apiPlatDataExchangeAnXinFenQi = new ApiPlatDataExchangeAnXinFenQi();
        apiPlatDataExchangeAnXinFenQi.setChannel(CHANNEL_CODE);
        apiPlatDataExchangeAnXinFenQi.setTimestamp(timestamp);
        apiPlatDataExchangeAnXinFenQi.setBizParam(dataStr);
        String json = JsonUtils.toJson(apiPlatDataExchangeAnXinFenQi);
        return json;
    }

    @Override
    public String apply(ApiApplyParameter apiApplyParameter) {

        ApiPlatFormApplyAnXinFenQiData apiPlatFormApplyAnXinFenQiData = new ApiPlatFormApplyAnXinFenQiData();

        apiPlatFormApplyAnXinFenQiData.setPhone(apiApplyParameter.getPhone());
        apiPlatFormApplyAnXinFenQiData.setName(apiApplyParameter.getUserName());
        apiPlatFormApplyAnXinFenQiData.setProvince("");
        apiPlatFormApplyAnXinFenQiData.setCity(apiApplyParameter.getCity().replace("市", ""));
        apiPlatFormApplyAnXinFenQiData.setAge(Integer.valueOf(apiApplyParameter.getAge()));

        // sex 性别 1男2女
        String sex = apiApplyParameter.getSex();
        Integer sexChoose = ChooseEq.create()
                .when(sex, "0", 1)
                .when(sex, "1", 2)
                .end();
        apiPlatFormApplyAnXinFenQiData.setSex(sexChoose);

        // loanAmount 预贷款额度
        String loanAmount = apiApplyParameter.getLoanAmount();
        if (ValidParam.isNotEmpty(loanAmount)) {
            Integer money = ChooseEq.create()
                    .when(loanAmount, "1", 30000)
                    .when(loanAmount, "2", 50000)
                    .when(loanAmount, "3", 100000)
                    .when(loanAmount, "4", 200000)
                    .end();
            apiPlatFormApplyAnXinFenQiData.setLoan(money);
        }

        //  loanTerm 贷款期限
        apiPlatFormApplyAnXinFenQiData.setLoanTerm(3);

        // loan_use 贷款用途
        String loanUser = apiApplyParameter.getLoanPurpose();
        if (ValidParam.isNotEmpty(loanUser)) {
            Integer value = ChooseEq.create()
                    .when(loanUser, "1", 5)
                    .when(loanUser, "2", 4)
                    .when(loanUser, "3", 8)
                    .when(loanUser, "4", 3)
                    .when(loanUser, "5", 8)
                    .when(loanUser, "6", 6)
                    .end();
            apiPlatFormApplyAnXinFenQiData.setLoanUse(value);
        }

        // zhima 芝麻分:
        String sesameCredit = apiApplyParameter.getSesameCredit();
        if (ValidParam.isNotEmpty(sesameCredit)) {
            Integer value = ChooseEq.create()
                    .when(sesameCredit, "1", 2)
                    .when(sesameCredit, "2", 3)
                    .when(sesameCredit, "3", 4)
                    .when(sesameCredit, "4", 5)
                    .end();
            apiPlatFormApplyAnXinFenQiData.setZhima(value);
        }

        //  花呗
        String HuaBei = apiApplyParameter.getHbLimit();
        if (ValidParam.isNotEmpty(HuaBei)) {
            Integer value = ChooseEq.create()
                    .when(HuaBei, "1", 1)
                    .when(HuaBei, "2", 2)
                    .when(HuaBei, "3", 3)
                    .when(HuaBei, "4", 4)
                    .when(HuaBei, "5", 4)
                    .end();
            apiPlatFormApplyAnXinFenQiData.setHuabei(value);
        }

        //  白条
        String BaiTiao = apiApplyParameter.getBtLimit();
        if (ValidParam.isNotEmpty(BaiTiao)) {
            Integer value = ChooseEq.create()
                    .when(BaiTiao, "1", 1)
                    .when(BaiTiao, "2", 2)
                    .end(3);
            apiPlatFormApplyAnXinFenQiData.setBaitiao(value);
        }

        //  微粒贷
        apiPlatFormApplyAnXinFenQiData.setMicroLoan(1);

        // has 社保：
        String socialSecurity = apiApplyParameter.getSocialSecurity();
        if (ValidParam.isNotEmpty(socialSecurity)) {
            Integer value = ChooseEq.create()
                    .when(socialSecurity, "1", 1)
                    .end(2);
            apiPlatFormApplyAnXinFenQiData.setHas(value);
        }

        // fund 公积金:
        String providentFund = apiApplyParameter.getProvidentFund();
        if (ValidParam.isNotEmpty(providentFund)) {
            Integer value = ChooseEq.create()
                    .when(providentFund, "1", 1)
                    .end(2);
            apiPlatFormApplyAnXinFenQiData.setFund(value);
        }

        // vehicle  车产：
        String carInfo = apiApplyParameter.getCarInfo();
        if (ValidParam.isNotEmpty(carInfo)) {
            Integer value = ChooseEq.create()
                    .when(carInfo, "1", 1)
                    .end(2);
            apiPlatFormApplyAnXinFenQiData.setCar(value);
        }

        // house 房产：
        String realEstateInfo = apiApplyParameter.getRealEstateInfo();
        if (ValidParam.isNotEmpty(realEstateInfo)) {
            Integer value = ChooseEq.create()
                    .when(realEstateInfo, "1", 1)
                    .end(2);
            apiPlatFormApplyAnXinFenQiData.setHouse(value);
        }

        // insurance 保单保险:
        String insurancePolicy = apiApplyParameter.getInsurancePolicy();
        if (ValidParam.isNotEmpty(insurancePolicy)) {
            Integer value = ChooseEq.create()
                    .when(insurancePolicy, "1", 1)
                    .end(2);
            apiPlatFormApplyAnXinFenQiData.setInsurance(value);
        }

        // overdue 逾期状态:
        String overdue = apiApplyParameter.getOverdue();
        if (ValidParam.isNotEmpty(overdue)) {
            Integer value = ChooseEq.create()
                    .when(overdue, "1", 1)
                    .end(2);
            apiPlatFormApplyAnXinFenQiData.setOverdue(value);
        }

        // education 学历
        String education = apiApplyParameter.getEducationAttainment();
        if (ValidParam.isNotEmpty(education)) {
            Integer value = ChooseEq.create()
                    .when(education, "1", 1)
                    .when(education, "2", 2)
                    .when(education, "3", 3)
                    .when(education, "4", 4)
                    .when(education, "5", 5)
                    .when(education, "6", 6)
                    .end();
            apiPlatFormApplyAnXinFenQiData.setEdu(value);
        }

        // creditCard 信用卡
        String creditCard = apiApplyParameter.getCreditLimit();
        if (ValidParam.isNotEmpty(creditCard)) {
            Integer value = ChooseEq.create()
                    .when(creditCard, "1", 1)
                    .end(2);
            apiPlatFormApplyAnXinFenQiData.setCredit(value);
        }

        // working 职业身份
        String career = apiApplyParameter.getCareer();
        if (ValidParam.isNotEmpty(career)) {
            Integer value = ChooseEq.create()
                    .when(career, "1", 1)
                    .when(career, "2", 3)
                    .when(career, "3", 2)
                    .when(career, "4", 5)
                    .when(career, "5", 4)
                    .end();
            apiPlatFormApplyAnXinFenQiData.setWorking(value);
        }

        //  是否有企业
        if (ValidParam.isNotEmpty(career)) {
            Integer value = ChooseEq.create()
                    .when(career, "3", 2)
                    .end(1);
            apiPlatFormApplyAnXinFenQiData.setCompany(value);
        }

        //  客户IP
        apiPlatFormApplyAnXinFenQiData.setJoinip(apiApplyParameter.getIp());

        AES aes = AES.createEcb(KEY.getBytes());
        Long timeStamp = System.currentTimeMillis();
        String jsonStr = JsonUtils.toJson(apiPlatFormApplyAnXinFenQiData);
        String dataStr = aes.encryptToBase64Str(jsonStr);

        ApiPlatFormApplyAnXinFenQi apiPlatFormApplyAnXinFenQi = new ApiPlatFormApplyAnXinFenQi();
        apiPlatFormApplyAnXinFenQi.setChannel(CHANNEL_CODE);
        apiPlatFormApplyAnXinFenQi.setTimestamp(timeStamp);
        apiPlatFormApplyAnXinFenQi.setBizParam(dataStr);
        String json = JsonUtils.toJson(apiPlatFormApplyAnXinFenQi);
        return json;
    }

    @Override
    public RespPlatformPhoneMd5Apply respApply(String respJson) {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformPhoneMd5Apply.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("code"), 200)) {
            return RespPlatformPhoneMd5Apply.ofFail();
        }
        return RespPlatformPhoneMd5Apply.ofSuc();
    }

    @Override
    public RespPlatformPhoneMd5DataExchange respDataExchange(String respJson) {
        if (JsonUtils.get(respJson) == null) {
            return RespPlatformPhoneMd5DataExchange.ofFail();
        }
        if (!Eq.object(JsonUtils.get(respJson).getInteger("code"), 100)) {
            return RespPlatformPhoneMd5DataExchange.ofFail();
        }

        JSONObject resData = JsonUtils.get(respJson).getJSONObject("data");
        JSONArray resProtocolList = resData.getJSONArray("protocolList");

        BigDecimal price = resData.getBigDecimal("price");
        String companyName = resData.getString("companyName");
        String productName = resData.getString("productName");
        String logo = resData.getString("logo");
        List<ApiProtocol> protocolList = CollUtils.newArrayList(newList -> {
            if (ValidParam.isNotEmpty(resProtocolList)) {
                for (int i = 0; i < resProtocolList.size(); i++) {
                    JSONObject protocolObject = resProtocolList.getJSONObject(i);
                    ApiProtocol protocol = new ApiProtocol();
                    protocol.setProtocolName(protocolObject.getString("protocolName"));
                    protocol.setProtocolUrl(protocolObject.getString("protocolUrl"));
                    newList.add(protocol);
                }
            }
        });

        RespPlatformPhoneMd5DataExchange result = RespPlatformPhoneMd5DataExchange.ofSuc();


        result.setPrice(price);
        result.setLogoPath(logo);
        result.setDisplayName(companyName);
        result.setProductName(productName);
        result.setProtocolList(protocolList);
        return result;
    }

    @Override
    public RespPlatformNoticeApply parseApplyNotice(RequestVO requestVO) {
        return null;
    }

    @Override
    public Map<String, Object> respApplyNotice(ApiBizStatus apiBizStatus) {
        return Map.of();
    }
}
